//
//  GTRaidersController.m
//  GiftTalk
//
//  Created by Wan on 16/4/7.
//  Copyright © 2016年 Wan. All rights reserved.
//  攻略控制器

#import "GTRaidersController.h"
#import "GTRaidersCell.h"
#import "GTRaidersReuseView.h"
#import "GTRaiderHeaderView.h"
#import "GTRaidersCollection.h"
#import "GTChannel.h"
#import "GTChannelGroup.h"
#import "GTNetWorkManager.h"
#import <MJRefresh.h>
#import <MJExtension.h>
#import <SVProgressHUD.h>
#import <View+MASAdditions.h>
#import "GTChannelViewController.h"
#import "GTRaidersCollection.h"

@interface GTRaidersController () <GTRaiderHeaderViewDelegate>

@property (weak, nonatomic) UICollectionViewFlowLayout *flowLayout;
/** 攻略顶部滚动控件 */
@property (nonatomic, weak) GTRaiderHeaderView *headerView;
/** 顶部控件，模型数组 */
@property (strong, nonatomic) NSArray *collections;

/** 分类攻略模型数组 */
@property (strong, nonatomic) NSMutableArray *channelGroups;
/** 网络请求工具 */
@property (strong, nonatomic) GTNetWorkManager *shareNetWorkTool;

@end

@implementation GTRaidersController

#pragma mark - 懒加载
- (GTNetWorkManager *)shareNetWorkTool {
    if (!_shareNetWorkTool) {
        _shareNetWorkTool = [GTNetWorkManager shareNetWorkTool];
    }
    return _shareNetWorkTool;
}

- (NSMutableArray *)channelGroups {
    if (!_channelGroups) {
        _channelGroups = [NSMutableArray array];
    }
    
    return _channelGroups;
}

- (NSArray *)collections {
    if (!_collections) {
        _collections = [NSArray array];
    }
    return _collections;
}

#pragma mark - UICollectionViewFlowLayout初始化
- (instancetype)init {
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    self.flowLayout =flowLayout;
    
    return [super initWithCollectionViewLayout:flowLayout];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // self.clearsSelectionOnViewWillAppear = NO;
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    // 初始化容器控件 & 布局
    [self setupCollectionView];
    [self setupFlowLayout];
    [self setupRaiderHeaderView];
    
    // 加载头部视图数据
    [self loadHeaderViewData];  
    
    
}

#pragma mark - 初始化
- (void)setupCollectionView {
    // 注册头部视图 & 分组视图
    [self.collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([GTRaidersReuseView class]) bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:reuseHeaderIdentifier];
    [self.collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([GTRaidersCell class]) bundle:nil] forCellWithReuseIdentifier:reuseIdentifier];
    
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    [self.collectionView.mj_header beginRefreshing];
    self.collectionView.backgroundColor = [UIColor whiteColor];
}

- (void)setupFlowLayout {
    CGFloat kItemMargin = 10.0;
    CGFloat kSectionMargin = 5.0;
    
    // 间距设置
    self.flowLayout.minimumLineSpacing = kItemMargin;
    self.flowLayout.minimumInteritemSpacing = kItemMargin;
    self.flowLayout.sectionInset = UIEdgeInsetsMake(kItemMargin, kSectionMargin, 0, kSectionMargin);
    
    // 每个 cell 的大小
    self.flowLayout.headerReferenceSize = CGSizeMake(self.view.width, 50);
    CGFloat itemW = (GTScreenW - 5 * kItemMargin) * 0.25;
    CGFloat itemH = itemW * 1.5;
    self.flowLayout.itemSize = CGSizeMake(itemW, itemH);
    
}

- (void)setupRaiderHeaderView {
    GTRaiderHeaderView *headerView = [GTRaiderHeaderView raiderHeaderView];
    headerView.delegate = self;
    [self.collectionView addSubview:headerView];
    
    [headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.collectionView.mas_top);
        make.left.right.equalTo(self.view);
        make.height.equalTo(@150.0);
    }];
    [headerView layoutIfNeeded];
    
    self.collectionView.contentInset = UIEdgeInsetsMake(headerView.height, 0, 0, 0);
    self.collectionView.mj_header.ignoredScrollViewContentInsetTop = headerView.height;
    self.headerView = headerView;
    
}

#pragma mark - 加载数据
- (void)loadData {
    // 加载头部数据
    [self loadHeaderViewData];
    
    NSString *urlStr = @"v2/channel_groups/all?";
    
    // 处理头部刷控件状态
    if (self.channelGroups.count > 0) {
        [self.collectionView.mj_header endRefreshing];
        return;
    }
    
    [self.shareNetWorkTool GET:urlStr parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        self.channelGroups = [GTChannelGroup mj_objectArrayWithKeyValuesArray: responseObject[@"data"][@"channel_groups"]];
        // 刷新列表 & 刷新控件状态处理
        [self.collectionView reloadData];
        [self.collectionView.mj_header endRefreshing];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [SVProgressHUD showErrorWithStatus:@"网络繁忙，请稍后再试!"];
        [self.collectionView.mj_header endRefreshing];
    }];
    
}

- (void)loadHeaderViewData {
    NSString *urlStr = @"v2/collections?limit=6&offset=0";
    if (self.headerView.collections.count > 0) return;
    
    [self.shareNetWorkTool GET:urlStr parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        self.headerView.collections = [GTRaidersCollection mj_objectArrayWithKeyValuesArray:responseObject[@"data"][@"collections"]];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [SVProgressHUD showErrorWithStatus:@"网络繁忙，请稍后再试!"];
    }];
}

#pragma mark - <GTRaiderHeaderViewDelegate>
- (void)raiderHeaderViewDidClickCheckAllButton:(GTRaiderHeaderView *)headerView {
    GTLogFunc
}

- (void)raiderHeaderViewDidClickWithCollection:(GTRaidersCollection *)collection {
    GTChannelViewController *channelVc = [[GTChannelViewController alloc] init];
    
    channelVc.title = collection.title;
    channelVc.dataArrayName = @"items";
    channelVc.firstPageURLString = [self channelUrlWithNumber:collection.ID];
    
    [self.navigationController pushViewController:channelVc animated:YES];
}

#pragma mark <UICollectionViewDataSource>

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return self.channelGroups.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    GTChannelGroup *channelGroup = self.channelGroups[section];
    return channelGroup.channels.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    GTRaidersCell *cell = [GTRaidersCell cellWithCollectionView:collectionView forIndexPath:indexPath];
    
    // 模型赋值
    GTChannelGroup *channelGroup = self.channelGroups[indexPath.section];
    GTChannel *channel = channelGroup.channels[indexPath.item];
    cell.channel = channel;
    
    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
        
    GTRaidersReuseView *reuserView = [GTRaidersReuseView reuseViewWithCollectionView:collectionView forIndexPath:indexPath];
    
    GTChannelGroup *channelGroup = self.channelGroups[indexPath.section];
    reuserView.channelGroup = channelGroup;
    
    return reuserView;
}

#pragma mark <UICollectionViewDelegate>

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    GTChannelGroup *channelGroup = self.channelGroups[indexPath.section];
    GTChannel *channel = channelGroup.channels[indexPath.item];
    
    GTChannelViewController *channelVc = [[GTChannelViewController alloc] init];
    channelVc.view.backgroundColor = GTBackgroundColor;
    channelVc.title = channel.name;
    channelVc.dataArrayName = @"items";
    channelVc.firstPageURLString = [self channelUrlWithNumber:channel.ID];
    
    [self.navigationController pushViewController:channelVc animated:YES];
}

#pragma mark - 处理频道列表
- (NSString *)channelUrlWithNumber:(NSInteger)number {
    NSMutableString *channelUrl = [NSMutableString stringWithFormat:@"http://api.liwushuo.com/v2/channels/"];
    [channelUrl appendFormat:@"%ld", number];
    [channelUrl appendString:@"/items?limit=20&offset=0"];
    
    return channelUrl;
}

- (void)dealloc {
    [[GTNetWorkManager shareNetWorkTool].operationQueue cancelAllOperations];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
